//
//  FavCarViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/27.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "FavCarViewController.h"
#import "BottomBar.h"
#import "CarTableCellTableViewCell.h"
#import "CarlistCellMode.h"
#import "NoItemView.h"
#import "LoadingView.h"
#import "Puser.h"
#import "IndexCarModel.h"
#import <MJRefresh.h>
#import "UserInfoUpdateResde.h"
#import "CarDetailViewController.h"
#define KfavNumber @"10"

@interface FavCarViewController ()<UITableViewDataSource,UITableViewDelegate,BottomBarBtnClickDelegate,BottombarDataSource>{
    BOOL _isedting;
    BOOL _candelete;
}
@property (nonatomic,strong) BottomBar *bottombar;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) CarlistCellMode *cellmode;
@property (nonatomic,strong) LoadingView *loading;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) NSMutableArray *indexcararray;
@property (nonatomic,strong) NSMutableArray *patharray;
@property (nonatomic,weak) NoItemView *notitem;
@end

@implementation FavCarViewController
-(NSMutableArray *)indexcararray{
    if (_indexcararray==nil) {
        _indexcararray=[NSMutableArray array];
    }
    return _indexcararray;
}
-(NSMutableArray *)patharray{
    if (_patharray==nil) {
        _patharray=[NSMutableArray array];
    }
    return _patharray;
}
+(instancetype)Viewcontroller{
    FavCarViewController *favc=[[FavCarViewController alloc]init];
    favc.hidesBottomBarWhenPushed=YES;
    return favc;
}

-(void)BottomBarAllclick:(BottomBar *)bottombar{
        for (CarlistCellMode *mode in self.indexcararray) {
        mode.ischecked=bottombar.allselected;
    }
    [self.tableView reloadData];
}

-(NSInteger)numberofBottobarcount:(BottomBar *)bottombar{
    return self.indexcararray.count;
}

-(void)BottomBar:(BottomBar *)bottombar otherbtnClick:(NSInteger)index{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.labelText=@"正在取消";
    
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
   
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"cancel_fav";
    params[@"type"]=[self.user.power integerValue] <5?@"person":@"company";
    params[@"user_id"]=[self.user.power integerValue] <5?self.user.user_id:self.user.com_id;
   
    [self.patharray removeAllObjects];
   
    for (CarlistCellMode *mode in self.indexcararray) {
        
        if (mode.ischecked) {
            [self.patharray addObject:mode.cardmode.ID];
        }
       
    }
    params[@"car_id"]=[NSString DataTOjsonString:self.patharray];
    
    [PostUitls Post:myfavurl parameters:params success:^(id response) {
        
        UserInfoUpdateResde *resd=[UserInfoUpdateResde resdeWithDict:response];
        hud.mode = MBProgressHUDModeText;
        if ([resd.state integerValue]==400) {
            hud.labelText=@"取消收藏成功";
            _candelete=NO;
            _isedting=NO;
            [self.tableView.header beginRefreshing];
            self.bottombar.btnenable=_candelete;
            self.bottombar.allselected=_candelete;
            }else{
            hud.labelText=@"取消收藏失败";
        }
        
         [hud hide:YES afterDelay:1];
    } failure:^(NSError *error) {
        hud.mode = MBProgressHUDModeText;
         hud.labelText=@"网络错误";
         [hud hide:YES afterDelay:1];
    }];
    
}

-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

-(UITableView *)tableView{
    if (_tableView==nil) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, XHScreenheight) style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.backgroundColor=bgGarycolor;
        _tableView.separatorStyle=NO;
        // Uncomment the following line to preserve selection between presentations.
        // self.clearsSelectionOnViewWillAppear = NO;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 56, 0);
    self.navigationItem.title=@"收藏的车源";
    
    self.cellmode=[[CarlistCellMode alloc]init];
    NoItemView *noitem=[NoItemView viewWithType:FAVTYPE];
    [self.tableView addSubview:noitem];
    _notitem=noitem;
    
    
  
    [self setuptableView];
       // Do any additional setup after loading the view.
}

-(void)refresh{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"my_fav";
    params[@"type"]=[self.user.power integerValue]<5?@"person":@"company";
    params[@"user_id"]=[self.user.power integerValue]<5?self.user.user_id:self.user.com_id;
    params[@"num"]=KfavNumber;
    [PostUitls Post:myfavurl parameters:params success:^(id response) {
        NSDictionary *dict=response;
         [self.indexcararray removeAllObjects];
        IndexCarModel *carmode=[IndexCarModel indexcarWithDcit:dict];
        if ([carmode.state integerValue]==400) {
           
            NSMutableArray *marray=[NSMutableArray array];
            for (CarDetailmodel *cardetail in carmode.data) {
                CarlistCellMode *carlistcell=[[CarlistCellMode alloc]init];
                carlistcell.cardmode=cardetail;
                carlistcell.title=cardetail.shop_name;
                [marray addObject:carlistcell];
            }
            if (marray.count>=[KfavNumber integerValue]) {
                [self.tableView.footer resetNoMoreData];
            }else{
                [self.tableView.footer noticeNoMoreData];
            }
            if (marray.count==0) {
               
                self.navigationItem.rightBarButtonItem=nil;
                [self.notitem show];
                
            }else{
                
                [self.notitem hide];
                [self setupRight:NO];
            }
            [self.tableView.header endRefreshing];
            [self.indexcararray addObjectsFromArray:marray];
           
            [self.tableView reloadData];
        }else{
            [self.tableView.header endRefreshing];
            [self.notitem show];
            [self.tableView reloadData];
            
        }
    } failure:^(NSError *error) {
        
    }];

}

-(void)setuptableView{
    MJRefreshNormalHeader *header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.header=header;
    self.tableView.header.automaticallyChangeAlpha=YES;
    MJRefreshBackNormalFooter *footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget: self refreshingAction:@selector(loadmoredata)];
    self.tableView.footer=footer;
    self.tableView.footer.automaticallyChangeAlpha=YES;
    [self.tableView.header beginRefreshing];
}

-(void)loadmoredata{
    [self.tableView.footer endRefreshing];
}

-(void)rightclick{
    _isedting=!_isedting;
    [self setupRight:_isedting];
    [self.tableView reloadData];
    
}

-(void)setupRight:(BOOL)iseidting{
    if (iseidting) {
        UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
        [self.bottombar show];
        self.navigationItem.rightBarButtonItem=rightitem;
        
    }else{
        [self.bottombar hide];
        self.bottombar.allselected=NO;
        for (CarlistCellMode *mode in self.indexcararray) {
            mode.ischecked=self.bottombar.allselected;
        }
        UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
        
        self.navigationItem.rightBarButtonItem=rightitem;
    }
    
    
}


-(BottomBar *)bottombar{
    if (_bottombar==nil) {
        _bottombar=[[BottomBar alloc]initWithBtnTitleArray:@[@"删除"] WithDelegate:self :YES];
        _bottombar.ishwopost=NO;
        _bottombar.datasource=self;
        [_bottombar addInView:self.view];
    }
    return _bottombar;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.indexcararray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CarlistCellMode *mode=self.indexcararray[indexPath.row];
    
    CarTableCellTableViewCell *cell=[CarTableCellTableViewCell cellWithTableView:tableView];
    cell.carcellmode=mode;
    cell.isShowEidt=_isedting;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CarlistCellMode *mode=self.indexcararray[indexPath.row];
    return mode.rowheight;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_isedting) {
        CarlistCellMode *mode=self.indexcararray[indexPath.row];
        mode.ischecked=!mode.ischecked;
        CarTableCellTableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];
        cell.editbtn.selected=!cell.editbtn.selected;
        for (CarlistCellMode *carmode in self.indexcararray) {
            if (carmode.ischecked) {
                _candelete=YES;
                break;
            }else{
            _candelete=carmode.ischecked;
            }
        }
        self.bottombar.btnenable=_candelete;
    }else{
         CarlistCellMode *mode=self.indexcararray[indexPath.row];
        CarDetailViewController *cdvc=[CarDetailViewController viewcontroller];
        cdvc.ID=mode.cardmode.ID;
        [self.navigationController pushViewController:cdvc animated:YES];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
